(async () => {
    const html = `
        <style>
        #ScriptRoot {
            position: fixed;
            right: 50px;
            bottom: 50px;
        }

        #ScriptRoot .context {
            width: 500px;
            position: absolute;
            left: -100%;
            top: -100%;
        }

        .dialog {
            background: #fff;
            padding: 15px;
            position: fixed;
            z-index: 10000;
            left: 50%;
            top: 50%;
            transform: translateX(-50%) translateY(-50%);
            box-shadow: 0 0 20px 0 rgba(0, 0, 0, 0.3);
            border-radius: 15px;
            overflow-y: auto;
            max-height: 500px;
        }

        .dialogBtn {
            text-align: center;
            padding-top: 15px;
        }

        .dialogBtn button {
            cursor: pointer;
            padding-left: 15px;
            padding-right: 15px;
            height: 30px;
            background: #3f74e3;
            color: #fff;
            font-size: 14px;
            text-shadow: 1px -1px 0 rgba(0, 0, 0, 0.5);
            border: none;
            border-radius: 5px;
        }

        .dialogBtn button:hover {
            background: #1846a8;
        }

        .dialogContent {
            min-width: 500px;
            min-height: 80px;
            font-size: 16px;
            line-height: 1.5;
            display: flex;
            justify-content: center;
            align-items: center;
        }
        #ScriptContent {
            display: flex;
            gap: 2;
        }
    </style>
    <dialog class="dialog" id="ScriptDialog">
        <div class="dialogContent">
            <form id="ScriptForm">
                <div id="ScriptContent">
                </div>
            </form>
            <div class="dialogBtn">
                <button id="ScriptOkBtn">确定</button>
            </div>
        </div>
    </dialog>
    <div id="ScriptRoot">
        <div>
            <button id="ScriptShow">显示列表</button>
            <button id="ScriptStart">开始</button>
        </div>
    </div>
    `
    const container = document.createElement("div");
    container.innerHTML = html;
    document.body.appendChild(container)
    const startBtn = document.getElementById("ScriptStart")
    const showBtn = document.getElementById("ScriptShow");
    const dialog = document.getElementById("ScriptDialog")
    const dialogContent = document.getElementById("ScriptContent")
    const form = document.getElementById("ScriptForm")
    const dialogBtn = document.getElementById("ScriptOkBtn")
    showBtn.onclick = () => dialog.showModal()
    dialogBtn.onclick = () => dialog.close()
    const workflow = [{
        name: "文本审核",
        children: [{
            name: "人工审核（初审）",
            children: [
                "union_report_combinationdesc_c",
                "union_report_combinationname_c",
                "union_report_farmdesc_c",
                "union_report_farmmessage_c",
                "union_report_groupcontent_c",
                "union_report_groupcontent_e",
                "union_report_groupname_c",
                "union_report_groupname_e",
                "union_report_homedesc_c",
                "union_report_homemessage_c",
                "union_report_homewelcome_c",
                "union_report_mapdesc_c",
                "union_report_mapname_c",
                "union_report_name_c",
                "union_report_roomname_c",
                "union_report_sign_c",
                "union_report_talk_c",
                "yuanmeng_diy_text",
                "union_report_homename_c"
            ]
        }, {
            name: "人工审核（二审）",
            children: [
                "union_report_combinationdesc_c",
                "union_report_combinationname_c",
                "union_report_farmdesc_c",
                "union_report_farmmessage_c",
                "union_report_groupcontent_c",
                "union_report_groupcontent_e",
                "union_report_groupname_c",
                "union_report_groupname_e",
                "union_report_homedesc_c",
                "union_report_mapdesc_c",
                "union_report_mapname_c",
                "union_report_name_c",
                "union_report_roomname_c",
                "union_report_sign_c",
                "union_report_talk_c",
                "union_report_homename_c"

            ]
        }]
    }, {
        name: "图片审核",
        children: [{
            name: "人工审核（初审）",
            children: [
                "举报",
                "封面"
            ]
        }, {
            name: "人工审核（二审）",
            children: [{
                name: "举报",
                children: [
                    "129组合",
                    "130家园",
                    "多人测试举报",
                    "家园封面"

                ]
            }, {
                name: "封面",
                children: [
                    "141组合封面",
                    "178家园派对封面",
                    "179家园封面"
                ]
            }]
        }]
    }, {
        name: "富文本审核",
        children: [{
            name: "富文本审核（初审）",
            children: [
                "defaultchannel",
                "上架",
                "剧情图片",
                "本地图片",
                "高热"
            ]
        }, {
            name: "富文本审核（二审）",
            children: [{
                name: "上架",
                children: [
                    "129组合",
                    "130家园"
                ]
            },
                "剧情图片",
                "本地图片"
            ]
        }]
    }];

    const renderWorkflow = ({ name, children }, target = "") => {
        const dom = document.createElement("div")
        const title = document.createElement("div")
        title.innerText = name;
        dom.appendChild(title)
        const context = document.createElement("div")
        for (const child of children) {
            if (typeof child === "string") {
                const item = document.createElement("div")
                const checkbox = document.createElement("input")
                checkbox.type = "checkbox"

                checkbox.name = "locnelor_checkbox"
                checkbox.value = `${target}_locnelor_${name}_locnelor_${child}`

                const label = document.createElement("label");
                label.innerText = child
                item.appendChild(label)
                item.appendChild(checkbox)
                context.appendChild(item)
            } else {
                context.append(renderWorkflow(child, `${target}_locnelor_${name}`))
            }
        }
        dom.appendChild(context)
        return dom;
    }
    for (const workItem of workflow) {
        const dom = renderWorkflow(workItem)
        dialogContent.appendChild(dom)
    }


    const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

    let menu;
    do {
        try {
            const menuList = Array.from(document.getElementsByClassName("submenu-wrapper")[0].children);
            menu = menuList.reduce((acc, item) => {
                acc[item.getElementsByTagName("span")[1].innerText] = item;
                return acc
            }, {});
        } catch (e) { }
        await sleep(500);
    } while (!menu);
    let status = false;
    let time;
    const getIframeDocument = () => {
        const iframe = document.getElementsByTagName("iframe")[0];
        const iframeDocument = iframe.contentWindow.document
        return iframeDocument
    }
    const getQueryButton = async () => {
        const iframeDocument = getIframeDocument();
        let button;
        do {
            try {
                button = iframeDocument.getElementsByClassName("el-button query-btn el-button--primary")[0]
            } catch (e) { }
            await sleep(500);
        } while (!button)
        return button
    }
    const query = async () => {
        await sleep(1200)
        const btn = await getQueryButton();
        btn.click();
        const iframeDocument = getIframeDocument();
        const task = iframeDocument.getElementsByClassName("task")[0];
        let text = "";
        do {
            try {
                await sleep(100)
                const num = task.getElementsByClassName("num")[0];
                text = num.innerText;
            } catch (e) { }
        } while (text.includes("加载中") || !text);
        return text.split("").reduce((count, word) => {
            const n = parseInt(word);
            if (!word || isNaN(n)) return count;
            return count * 10 + n;
        }, 0);
    }
    const getQueryItems = async () => {
        let header
        do {
            const iframeDocument = getIframeDocument()
            header = iframeDocument.getElementsByClassName("header")[0];
            await sleep(1000);
        } while (!header);
        return Array.from(header.getElementsByClassName("query-item"));
    }
    const getDomItems = async (dom) => {
        const iframeDocument = getIframeDocument()
        dom.getElementsByTagName("input")[0].click();
        await sleep(500)
        const item = Array.from(iframeDocument.getElementsByClassName("el-select-dropdown el-popper")).find(e => {
            return e.style.display !== "none";
        });
        await sleep(500)
        dom.getElementsByTagName("input")[0].click();
        return Array.from(item.getElementsByTagName("li"))
    }
    const getWork = async () => {
        const iframeDocument = getIframeDocument();
        let btn;
        do {
            btn = Array.from(iframeDocument.getElementsByTagName("button")).find(e => e.innerText === "领取任务")
        } while (!btn);
        btn.click();
    }



    const setThreeDay = async () => {
        const iframeDocument = getIframeDocument();
        const label = Array.from((iframeDocument.getElementsByClassName("el-radio-button"))).find(e => e.innerText === "近3天")
        if (!label) return;
        label.getElementsByTagName("input")[0].click()
        await sleep(500)
    }
    const queryAndGet = async (arr, key) => {
        const num = await query();
        if (num == 0) return;
        await sleep(500)
        await getWork();
        console.log(arr, key)
        // speech = new SpeechSynthesisUtterance()
        // speech.text = '领取到任务了'
        // speech.pitch = 1 // 设置话语的音调(0-2 默认1，值越大越尖锐,越低越低沉)
        // speech.rate = 0.9 // 设置说话的速度(0.1-10 默认1，值越大语速越快,越小语速越慢)
        // speech.volume = 10 // 设置说话的音量
        // speech.lang = 'zh-CN' // 设置播放语言
        // speechSynthesis.speak(speech)

        await sleep(3000)
    }

    let currentKey;
    let currentTypeMenu = {};
    const setCurrentTypeMenu = async (key) => {
        menu[key].click()
        await sleep(1000);
        const [typeItem, valueItem] = await getQueryItems();
        const types = await getDomItems(typeItem);
        currentTypeMenu = {};
        for (const type of types) {
            type.click();
            const name = type.innerText;
            const menu = await getDomItems(valueItem);
            currentTypeMenu[name] = {
                dom: type,
                menu
            }
            await sleep(500)
            type.click()
        }
        await sleep(500)
        menu[key].click()
        await sleep(500)
    }
    let currentTypeMenuCopy = {};
    const setCurrentCopyMenu = async () => {
        const [typeItem, valueItem, lineItem] = await getQueryItems();
        const types = await getDomItems(lineItem);
        for (const type of types) {
            currentTypeMenuCopy[type.innerText] = type
        }
        await sleep(500)
    }
    let workObj = {};
    function* factor() {
        for (const menu of workflow) {//选择页面
            const key = menu.name;
            if (!workObj[key]) continue;
            if (currentKey !== key) {
                currentKey = key;
                yield setCurrentTypeMenu(key);
            }
            yield setThreeDay();
            for (const item of menu.children) {
                const type = item.name
                if (!workObj[key]?.[type]) continue;
                if (!currentTypeMenu[type]) {
                    continue;
                }
                currentTypeMenu[type].dom.click();//选择类型
                yield sleep(1000);
                for (const line of item.children) {
                    if (typeof line === "string") {
                        if (!workObj[key]?.[type]?.[line]) continue;
                        const dom = currentTypeMenu[type].menu.find(e => e.innerText === line)
                        if (!dom) {
                            console.log(`找不到 ${key}-${type}-${line}`)
                            continue;
                        } else {
                            console.log("click", dom.innerText)
                            dom.click()
                        }
                        yield sleep(1000);
                        console.log(`${key}-${type}-${line}`)
                        yield queryAndGet(
                            [key, type],
                            line
                        )
                    } else {
                        const typeChild = line.name;
                        const dom = currentTypeMenu[type].menu.find(e => e.innerText === line.name)
                        if (!dom) {
                            console.log(`找不到 ${key}-${type}-${typeChild}-${line.name}`)
                            continue;
                        } else {
                            dom.click()
                        }
                        yield sleep(500);
                        yield setCurrentCopyMenu()
                        for (const n of line.children) {
                            if (!workObj[key]?.[type]?.[typeChild]?.[n]) continue;
                            const dom = currentTypeMenuCopy[n]
                            if (!dom) {
                                console.log(`找不到 ${key}-${type}-${typeChild}-${n}`)
                                continue;
                            } else {
                                dom.click()
                            }
                            yield sleep(500);
                            console.log(`${key}-${type}-${typeChild}-${n}`)
                            yield queryAndGet(
                                [key, type, typeChild],
                                n
                            );
                        }
                    }
                }
            }
        }
    }
    const isEmptyWork = () => {
        const iframeDocument = getIframeDocument();
        const table = Array.from(iframeDocument.getElementsByTagName("span"))
        return !!table.find(e => e.innerText === "请先领取任务")
    }
    let work;
    const start = async () => {
        work = factor();
        currentKey = "";

        const data = new FormData(form)
        const list = [];
        data.forEach(line => {
            list.push(line.split("_locnelor_").slice(1))
        })
        workObj = {};
        for (const arr of list) {
            let obj = workObj;
            for (const key of arr) {
                if (!obj[key]) obj[key] = {};
                obj = obj[key];
            }
        }
        while (status) {
            if (!isEmptyWork()) {
                console.log("continue")
                await sleep(1000);
                continue;
            }
            const { done, value } = work.next();
            try {
                if (done) work = factor();
                else await value.catch((e) => console.log(e))
            } catch (e) {
                console.log("error", e)
            }
        }
    }
    const close = () => {
        clearTimeout(time);
    }
    const onclick = () => {
        status = !status;
        startBtn.innerText = status ? "暂停" : "开始"
        if (status) start()
        else close()
    }
    startBtn.onclick = onclick
})()